#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
THN HTTP Stack Library
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 01-May-14 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Text;

using Thn;
using Thn.IO;
using Thn.Text;
#endregion

namespace Thn.Net.Http
{
    /// <summary>
    /// This class implements form data parsing with the "application/x-url-encoded" or "application/x-www-form-urlencoded" scheme.
    /// For more information, please refer to:
    /// http://en.wikipedia.org/wiki/POST_(HTTP)
    /// </summary>
#if DEBUG || TESTING
    public
#else
    public
#endif
 class UrlEncodedFormDataParser : FormDataParserBase
    {
        #region Fields
        #endregion

        #region Properties
        #endregion

        #region On Parse
        /// <summary>
        /// Parse <see cref="FormData"/> from the provided request.
        /// </summary>
        /// <param name="reader">The reader to read from.</param>
        protected override FormData OnParse(IContextReader reader)
        {
            FormData result = new FormData();

            if (reader.Length > 0)
            {
                var processor = new CharProcessor();
                processor.Reader = reader;
                bool keepProcessing = true;
                int marker;
                StringBuilder builder;
                string name;
                string value;

                while (!processor.IsEnded && keepProcessing)
                {
                    #region Read name
                    
                    builder = new StringBuilder();
                    marker = processor.ReadUntil(builder, true, false, true, '=', '\r', '\n');
                    
                    if (marker == '=')
                    {
                        #region Found end of name

                        if (builder.Length > 0)
                        {
                            name = builder.ToString();
                            builder = new StringBuilder();
                        }
                        #region Defensive tracing
                        else
                        {
                            //error, quit
                            break;
                        }
                        #endregion

                        #endregion
                    }
                    else
                    {
                        #region Unexpected -> quit

                        keepProcessing = false;
                        break;

                        #endregion
                    }

                    #endregion

                    #region Read value

                    marker = processor.ReadUntil(builder, true, false, true, '&', '\r', '\n');

                    if (builder.Length > 0)
                    {
                        value = builder.ToString();

                        //replace + with space
                        value = value.Replace('+', ' ');
                        
                        //URL decode
                        value = UrlEscape.Decode(value);

                        //add item
                        var item = new FormDataItem();
                        item.Name = name;
                        item.Value = value;
                        result.Items.Add(item.Name, item);
                    }
                    #region Defensive tracing
                    else
                    {
                        //error, quit
                        break;
                    }
                    #endregion

                    #endregion
                }
            }

            return result;
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Create a new instance.
        /// </summary>
        public UrlEncodedFormDataParser()
            : base()
        { }
        #endregion
    }
}
